package com.teampuzzle;



import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements SurfaceHolder.Callback{

private static final String TAG = GameView.class.getSimpleName();
	
	private GameThread thread;
	//private Droid droid;

	public GameView(Context context) {
		super(context);
		// adding the callback (this) to the surface holder to intercept events
		getHolder().addCallback(this);

		// create droid and load bitmap
		//droid = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.droid_1), 50, 50);
		
		// create the game loop thread
		thread = new GameThread(getHolder(), this, context);
		
		// make the GamePanel focusable so it can handle events
		setFocusable(true);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// at this point the surface is created and
		// we can safely start the game loop
		thread.setRunning(true);
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.d(TAG, "Surface is being destroyed");
		// tell the thread to shut down and wait for it to finish
		// this is a clean shutdown
		boolean retry = true;
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// try again shutting down the thread
			}
		}
		Log.d(TAG, "Thread was shut down cleanly");
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			// delegating event handling to the droid
			thread.myPuzzle.handleActionDown((int)event.getX(), (int)event.getY());
			thread.myPlayer.handleActionDown((int)event.getX(), (int)event.getY());
			
		}
		return true;
	}
	
	public void updateBg(Canvas canvas){
		if(thread.myPlayer.multiplier==1){
			canvas.drawBitmap(GameThread.background_texture, 0, 0, null);
			} else if(thread.myPlayer.multiplier==2){
				canvas.drawBitmap(GameThread.background_texturex2, 0, 0, null);
			} else if(thread.myPlayer.multiplier==3){
				canvas.drawBitmap(GameThread.background_texturex3, 0, 0, null);
			} else if(thread.myPlayer.multiplier==4){
				canvas.drawBitmap(GameThread.background_texturex4, 0, 0, null);
			}
			
	}

	public void render(Canvas canvas) {
		
		updateBg(canvas);
		
		if(GameThread.mMode == GameThread.STATE_GAMELOOSE){
			// GAME LOOSE
			Log.d(TAG, "GAME LOOSE");
			//GameThread.running = false;
			//DrawDebug(canvas, 20.0f);
			
			thread.myPlayer.drawEndScreen(canvas);
			
			if(thread.myPlayer.restartButtonPressed){
				thread.myPlayer = new Player();
				thread.mMode = thread.STATE_NEWLEVEL;
			}
			
		}else if(GameThread.mMode == GameThread.STATE_PUZZLEWIN){
			// PUZZLE WIN
			Log.d(TAG, "PUZZLE WIN");
			
		}else if(GameThread.mMode == GameThread.STATE_PUZZLELOOSE){
			// PUZZLE LOOSE
			Log.d(TAG, "PUZZLE LOOSE");
			
		}else if(GameThread.mMode == GameThread.STATE_NEWLEVEL){
			// NEW LEVEL
			Log.d(TAG, "NEW LEVEL");
			
		} else{
			// PUZZLE IS RUNNING
			
			//canvas.drawColor(Color.BLACK);
			
			thread.myPlayer.printScore(canvas);
			//thread.myPuzzle.draw(canvas);
			thread.myPlayer.printTime(canvas);
			
		}
		
		
		//droid.draw(canvas);
	}
	
	public void DrawDebug(Canvas canvas, float n){
		Paint mLinePaint = new Paint();
		mLinePaint.setARGB(255, 0, 255, 0);
		canvas.drawText("" + n, 120,40, mLinePaint);
	}

	/**
	 * This is the game update method. It iterates through all the objects
	 * and calls their update method if they have one or calls specific
	 * engine's update method.
	 */
	public void update() {
		// check collision with right wall if heading right
		
		// Update the lone droid
		//droid.update();
	}

//	
//	//used to keep track of time between updates and amount of time to sleep for
//   // long lastUpdate = 0;
//   // long sleepTime=0;
//    //Game engine
//    GameThread myGameThread;
//
//    //objects which house info about the screen
//    //SurfaceHolder surfaceHolder;
//    Context mContext;
// 
//    //our Thread class which houses the game loop
//    //private GameThread thread;
// 
//    //initialization code
//    /*void InitView(){
//      //initialize our screen holder
//      SurfaceHolder holder = getHolder();
//      holder.addCallback( this);
//
//      //initialize our game engine
//      myGameThread = new GameThread();
//      myGameThread.Init(context.getResources());
//  
//      //initialize our Thread class. A call will be made to start it later
//      thread = new GameThread(holder, context, new Handler(), myGameThread);
//      setFocusable(true);
//   } */
// 
//   //class constructors
// 
//   public GameView(Context contextS, AttributeSet attrs){
//	   super(contextS, attrs);
//       
//       // register our interest in hearing about changes to our surface
//       SurfaceHolder holder = getHolder();
//       holder.addCallback(this);
//
//       // create thread only; it's started in surfaceCreated()
//       //myGameThread = new GameThread(holder, context, null);
//       myGameThread = new GameThread(holder, contextS, new Handler()
//       {
//           @Override
//           public void handleMessage(Message m)
//           {
//               //mStatusText.setVisibility(m.getData().getInt("viz"));
//               //mStatusText.setText(m.getData().getString("text"));
//           }
//       });
//
//       setFocusable(true); // make sure we get key events
//   }
// 
//
////[Various code to capture key presses, screen changes and screen touch events]
//
//
//
//    //these methods are overridden from the SurfaceView super class. They are automatically called 
//   // when a SurfaceView is created, resumed or suspended.
//   public void surfaceCreated(SurfaceHolder holder)
//   {
//       // start the thread here so that we don't busy-wait in run()
//       // waiting for the surface to be created
//   	myGameThread.setRunning(true);
//   	myGameThread.start();
//   }
//   
//   /*
//    * Callback invoked when the Surface has been destroyed and must no longer
//    * be touched. WARNING: after this method returns, the Surface/Canvas must
//    * never be touched again!
//    */
//   public void surfaceDestroyed(SurfaceHolder holder)
//   {
//       // we have to tell thread to shut down & wait for it to finish, or else
//       // it might touch the Surface after we return and explode
//       boolean retry = true;
//       myGameThread.setRunning(false);
//       
//       while (retry)
//       {
//           try
//           {
//               myGameThread.join();
//               retry = false;
//           }
//           catch (InterruptedException e)
//           {
//           }
//       }
//   }
//   
//   /* Callback invoked when the surface dimensions change. */
//   public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
//   {
//       myGameThread.setSurfaceSize(width, height);
//   }
//   
//   /**
//    * Fetches the animation thread corresponding to this LunarView.
//    * 
//    * @return the animation thread
//    */
//    public GameThread getThread()
//    {
//        return myGameThread;
//    }
	


}
